package com.demo.batch.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.TaskletStep;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 *
 * @author
 * @since
 */
@Component
@Slf4j
public class JobFactory {

  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Autowired
  private StepBuilderFactory stepBuilderFactory;

  @Autowired
  private DemoItemReader demoItemReader;

  @Autowired
  private DemoItemWriter demoItemWriter;

  @Autowired
  private DemoProcessor demoProcessor;

  public Job getJobInstance(){
    Step step1 = stepBuilderFactory.get("step1")
        .<String, String> chunk(10)
        .reader(demoItemReader)
        .processor(demoProcessor)
        .writer(demoItemWriter)
        .listener(new StepExecutionListener() {
          @Override
          public void beforeStep(StepExecution stepExecution) {
            log.info("step before   ");
          }

          @Override
          public ExitStatus afterStep(StepExecution stepExecution) {
            log.info("after step   ");
            return stepExecution.getExitStatus();
          }
        })
        .build();

    ((TaskletStep) step1).registerChunkListener(new ChunkListener() {
      @Override
      public void beforeChunk(ChunkContext context) {
        log.info("Job before chunk  ");
      }

      @Override
      public void afterChunk(ChunkContext context) {
        log.info("Job after chunk  ");
      }

      @Override
      public void afterChunkError(ChunkContext context) {
        log.info("Job after chunk error");
      }
    });


    return jobBuilderFactory.get(UUID.randomUUID().toString())
        .incrementer(new RunIdIncrementer())
        .listener(new JobExecutionListener() {
          @Override
          public void beforeJob(JobExecution jobExecution) {
            log.info("Job  before start ");
          }

          @Override
          public void afterJob(JobExecution jobExecution) {
            log.info("After job done ");
          }
        })
        .flow(step1)
        .end()
        .build();
  }


}
